var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//引入路由
var apiRouter = require('./routes/apiAdmin');

var app = express();
var favicon = require('serve-favicon')
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
const session = require('express-session');
app.use(session({
    name: 'uid', // 这里是cookie的name，默认是connect.sid
    secret: 'my_session_secret', // 建议使用 128 个字符的随机字符串
    resave: false, //制保存session，即使它没有变化
    saveUninitialized: true, //保存未初始化的值,减轻服务器压力
    rolling: false, //每次响应是否重新设置cookie的maxAge., true
    cookie: { maxAge: 60 * 60 * 24 * 7 * 1000, httpOnly: true } //60秒
}));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', "Content-Type,Authorization");
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});


const jwt = require('jsonwebtoken');
let secretOrPrivateKey = "cxblog"; //加密的key
//token验证
app.use(function(req, res, next) {
    // console.log('进入验证' + req.originalUrl)
    // 1.如果是不是登录界面或者注册界面，就验证token是否存在
    console.log(req.originalUrl)
    if (req.originalUrl != '/api/login' && req.originalUrl != '/api/register' && req.originalUrl != '/api/agent/login') {
        let token = req.get('Authorization');
        if (token == null || token == '') return res.json({ code: 401, msg: 'token无效' })
        jwt.verify(token, secretOrPrivateKey, function(err, decode) {
            if (err) { //  时间失效的时候/ 伪造的token          
                res.json({
                    code: 401,
                    msg: 'token过期'
                })
                return;
            } else {
                next();
            }
        })

    } else {
        next();
    }
})

// 挂载api路由
app.use('/api', apiRouter);

app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;